import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref('')
  const userInfo = ref({
    id: 0,
    name: '', // 真实姓名
    username: '',
    role: '',
    deptId: 0,
    deptName: '',
  })
  const permissions = ref<string[]>([])

  // 设置用户信息
  const setUserInfo = (info: any) => {
    userInfo.value = {
      id: info.id || 0,
      name: info.name || '', // 新增真实姓名字段
      username: info.username || '',
      role: info.role || '',
      deptId: info.deptId || 0,
      deptName: info.deptName || '',
    }

    // 设置权限
    if (info.permissions && Array.isArray(info.permissions)) {
      permissions.value = info.permissions
    } else {
      // 根据角色设置默认权限
      permissions.value = getDefaultPermissions(info.role || '')
    }
  }

  // 获取默认权限
  const getDefaultPermissions = (role: string) => {
    const rolePermissions: Record<string, string[]> = {
      admin: ['*'],
      manager: [
        'user:read',
        'user:write',
        'crm:view',
        'crm:customer:view',
        'crm:followup:view',
        'crm:order:view',
        'crm:review:view',
      ],
      employee: [
        'user:read',
        'crm:view',
        'crm:customer:view',
        'crm:followup:view',
        'crm:order:view',
      ],
    }
    return rolePermissions[role] || []
  }

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除用户信息
  const clearUserInfo = () => {
    token.value = ''
    userInfo.value = {
      id: 0,
      name: '',
      username: '',
      role: '',
      deptId: 0,
      deptName: '',
    }
    permissions.value = []
    localStorage.removeItem('token')
  }

  // 登出
  const logout = () => {
    clearUserInfo()
  }

  // 初始化用户信息
  const initUserInfo = () => {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      // 这里可以添加获取用户信息的API调用
    }
  }

  return {
    token,
    userInfo,
    permissions,
    setUserInfo,
    setToken,
    clearUserInfo,
    logout,
    initUserInfo,
  }
})
